#include "udpcommunicate.h"

#include <QSettings>
#include <QDebug>

UDPCommunicate::UDPCommunicate(QString localIp, QString remoteIp,int localPort ,int remotePort, QObject *parent) : QObject(parent)
{
    m_local_ip  = localIp;
    m_remote_ip = remoteIp;
    m_local_port = localPort;
    m_remote_port = remotePort;
}

UDPCommunicate::~UDPCommunicate()
{
    slot_stop();
}

void UDPCommunicate::slot_init()
{

    m_udpSocket = new QUdpSocket(this);
    qDebug()<<"m_local_port"<<m_local_port;
    m_udpSocket->bind(QHostAddress(m_local_ip),m_local_port);// 创建UDP套接字对象用于接收数据
    connect(m_udpSocket, SIGNAL(readyRead()), this, SLOT(slot_receive()));               // 信号与槽连接后，触发信号会执行槽函
}

void UDPCommunicate::slot_send(QByteArray array)
{
    //qDebug()<<"in slot_send"<<m_remoteIp<<m_port;
    m_udpSocket->writeDatagram(array.data(),array.size(),(QHostAddress)m_remote_ip,m_remote_port);
}
void UDPCommunicate::slot_stop()
{
    disconnect(m_udpSocket, 0, 0, 0);
    // 关闭接收套接字
    m_udpSocket->close();
    m_udpSocket->deleteLater();
    delete m_udpSocket;
}
void UDPCommunicate::slot_receive()
{
    QByteArray   datagram;
    QHostAddress senderIP = QHostAddress(m_remote_ip);
    quint16      portx    = m_local_port;
    // qDebug()<<"UDPCommunicate"<<QThread::currentThreadId();

    // 设置data的大小为等待处理的数据报的大小，这样才能接收到完整的数据
    datagram.resize(m_udpSocket->pendingDatagramSize());
    // 接收数据报，将其存放到datagram中
    m_udpSocket->readDatagram(datagram.data(), datagram.size(), &senderIP, &portx);
    //    qDebug() << senderIP << datagram.size();
    // 处理接收数据
    if(datagram.size()>1)
        _handle(datagram);
}
void UDPCommunicate::_handle(const QByteArray &src)
{
    qDebug()<<"in udp handle";

    //处理收到的json数据包 测试了心跳 ok
    QJsonParseError jsonError;
    QJsonDocument doucment = QJsonDocument::fromJson(src, &jsonError);  // 转化为 JSON 文档
    if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError)) {  // 解析未发生错误
        if (doucment.isObject()) { // JSON 文档为对象
            QJsonObject object = doucment.object();  // 转化为对象
            if (object.contains("data_info")) {  // 包含指定的 key
                 QJsonValue value_datainfo = object.value("data_info");  // 获取指定 key 对应的 value
                if (value_datainfo.isObject()) {  // 判断 value 是否为对象
                     QJsonObject object_datainfo = value_datainfo.toObject();  // 转化为对象
                    if (object_datainfo.contains("data_type")){
                        QJsonValue value_datainfo_datatype = object_datainfo.value("data_type");  // 获取指定 key 对应的 value
                        if(value_datainfo_datatype.isString()){
                            QString strName = value_datainfo_datatype.toString();  // 将 value 转化为字符串
                            qDebug()<<"udp strName=data_type"<<strName;
                        }

                    }
                }

            }
        }
    }

}
